package com.elm.dao;

import com.elm.entity.Food;
import com.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class FoodDao {
    public List<Food> getFoodsByBusinessId(String businessId) {
        String sql = "select * from food where businessId=?";
        List<Food> foods = new ArrayList<>();

        try(Connection connection = DBUtil.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setString(1, businessId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Food food = new Food();
                packageFood(food, rs);
                foods.add(food);
            }

            return foods;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Food getFoodById(int foodId) {
        String sql = "select * from food where foodId=?";
        Food food = new Food();
        try(Connection connection = DBUtil.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setInt(1, foodId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                packageFood(food, rs);
            }

            return food;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private void packageFood(Food food, ResultSet rs) throws SQLException {
        food.setFoodId(rs.getInt("foodId"));
        food.setFoodName(rs.getString("foodName"));
        food.setFoodPrice(rs.getDouble("foodPrice"));
        food.setFoodImg(rs.getString("foodImg"));
        food.setFoodExplain(rs.getString("foodExplain"));
        food.setRemarks(rs.getString("remarks"));
    }
}